package com.fly.keyvalue.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fly.core.model.JsonResult;
import com.fly.keyvalue.entity.User;
import com.fly.keyvalue.service.UserService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "Restful用户接口")
@CrossOrigin
@RestController
@RequestMapping("/rest/users")
public class RestUserController
{
    @Autowired
    private UserService userService;
    
    @ApiOperation("分页查询")
    @ApiOperationSupport(order = 10)
    @GetMapping
    public JsonResult<Page<User>> list(@RequestParam int pageNo)
    {
        pageNo = Math.max(pageNo, 0);
        Page<User> page = userService.page(pageNo);
        return JsonResult.success(page);
    }
    
    @ApiOperation("查询")
    @ApiOperationSupport(order = 20)
    @GetMapping("/{id:\\d+}")
    public JsonResult<User> get(@PathVariable Long id)
    {
        User user = userService.get(id);
        return JsonResult.success(user);
    }
    
    @ApiOperation("新增、更新")
    @ApiOperationSupport(order = 30)
    @PutMapping
    public JsonResult<String> add(@RequestBody
    @Valid User user)
    {
        userService.saveOrUpdate(user);
        return JsonResult.success("保存成功");
    }
    
    @ApiOperation("删除")
    @ApiOperationSupport(order = 40)
    @DeleteMapping("/{id:\\d+}")
    public JsonResult<String> delete(@PathVariable Long id)
    {
        userService.delete(id);
        return JsonResult.success("删除成功");
    }
}
